#include "string.h"

#include "debug.h"
#include "global.h"

void memset(void* dst_, uint32_t size, uint8_t value)
{
  ASSERT(dst_ != NULL);

  uint8_t* dst = (uint8_t*)dst_;
  while (size-- > 0)
  {
    *dst++ = value;
  }
}

void memcpy(const void* src_, void* dst_, uint32_t size)
{
  ASSERT(src_ != NULL && dst_ != NULL);

  uint8_t* src = (uint8_t*)src_;
  uint8_t* dst = (uint8_t*)dst_;
  while (size-- > 0)
  {
    *src++ = *dst++;
  }
}

int memcmp(const void* a_, const void* b_, uint32_t size)
{
  ASSERT(a_ != NULL && b_ != NULL);

  uint8_t *a = (uint8_t*)a_, *b = (uint8_t*)b_;
  while (size-- > 0)
  {
    if (*a++ != *b++) return false;
  }
  return true;
}

char* strcpy(const char* src_, char* dst_)
{
  ASSERT(src_ != NULL && dst_ != NULL);

  char* start_of_new = dst_;
  while ((*dst_++ = *src_++))
    ;
  return start_of_new;
}

uint32_t strlen(const char* str)
{
  ASSERT(str != NULL);

  char* p_start = (char*)str;
  while (*str++)
    ;
  return (str - p_start - 1);
}

char* strchr(const char* str, const uint8_t ch)
{
  ASSERT(str != NULL);

  while (str++)
  {
    if (*str == ch)
    {
      return (char*)str;
    }
  }

  return NULL;
}

char* strrchr(const char* str, const uint8_t ch)
{
  ASSERT(str != NULL);

  char* last_char = NULL;
  while (*str++)
  {
    if (*str == ch)
    {
      last_char = (char*)str;
    }
  }
  return last_char;
}

char* strcat(char* dst_, const char* src_)
{
  ASSERT(dst_ != NULL && src_ != NULL);

  char* str = dst_;
  while (*str++)
    ;

  --str;
  // while str=0,string ends
  while ((*str++ = *src_++))
    ;
  return dst_;
}

uint32_t strchrs(const char* str, uint8_t ch)
{
  ASSERT(str != NULL);

  uint32_t ch_cnt = 0;
  while (*str++)
  {
    if (*str == ch)
    {
      ch_cnt++;
    }
  }

  return ch_cnt;
}
